<template>
  <div class="app-container">
    <div class="page-header">
      <h1>今日课程安排</h1>
      <p>{{ currentDate }}</p>
    </div>

    <div class="course-list">
      <div v-if="courses.length === 0" class="empty-state">
        <el-empty description="今日暂无课程安排"></el-empty>
      </div>

      <el-card v-for="course in courses" :key="course.id" class="course-card"
               :shadow="selectedCourse && course.id === selectedCourse.id ? 'hover' : 'hover'" @click.b.native="handleCourseClick(course)">
        <div class="course-info">
          <div class="course-header">
            <h3 class="course-name">{{ course.courseName }}</h3>
            <span class="course-time">{{ defaultData[course.sort - 1].time }}</span>
          </div>
          <div class="course-details">
            <div class="detail-item">
              <i class="el-icon-location"></i>
              <span>{{ course.location }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-user"></i>
              <span>班级: {{ course.className }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-s-custom"></i>
              <span>学生人数: {{ course.studentCount }}人</span>
            </div>
          </div>
          <div class="course-status" v-if="course.signInStatus">
            <el-tag :type="course.signInStatus.type" size="small">{{ course.signInStatus.text }}</el-tag>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 签到对话框 -->
    <el-dialog title="课程签到" :visible.sync="signInDialogVisible" width="800px" append-to-body>
      <div v-if="selectedCourse" class="sign-in-dialog">
        <div class="dialog-header">
          <h4>{{ selectedCourse.courseName }}</h4>
          <p>{{ defaultData[selectedCourse.sort - 1].time }} | {{ selectedCourse.location }}</p>
        </div>

        <div class="sign-in-actions">
          <el-button type="primary" @click="batchSignIn" :disabled="!canSignIn">
            <i class="el-icon-check"></i> 批量签到
          </el-button>
          <el-button @click="refreshSignInStatus">
            <i class="el-icon-refresh"></i> 刷新状态
          </el-button>
          <div class="sign-in-summary" v-if="signInSummary">
            <span>已签到: {{ signInSummary.signedCount }}人</span>
            <span>未签到: {{ signInSummary.notSignedCount }}人</span>
          </div>
        </div>

        <el-table :data="students" style="width: 100%" border>
          <el-table-column prop="name" label="学生姓名" ></el-table-column>
          <el-table-column label="签到状态" width="120">
            <template slot-scope="scope">
              <el-tag :type="scope.row.signed ? 'success' : 'warning'" size="small">
                {{ scope.row.signed ? '已签到' : '未签到' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="签到时间" >
            <template slot-scope="scope">
              {{ scope.row.signInTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作"  fixed="right">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="singleSignIn(scope.row)"
                :disabled="!canSignIn || scope.row.signed"
                :class="scope.row.signed ? 'text-disabled' : ''"
              >
                {{ scope.row.signed ? '已签到' : '签到' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeSignInDialog">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import {getCourseStudents, getSignInRecords, getTodayCourses, studentBatchSignIn, studentSignIn} from '@/api/ysg/work'
import course from "../classManage/course.vue";

const defaultData = [
  {
    time: '09:00-10:30',
  },
  {
    time: '10:30-12:00',
  },
  {
    time: '13:30-15:00',

  },
  {
    time: '15:00-16:30',

  },
  {
    time: '16:30-18:00',

  },
  {
    time: '18:00-19:30',
  }
]
export default {
  name: 'TodayCourses',
  computed: {
    course() {
      return course
    }
  },
  data() {
    return {
      courses: [],
      currentDate: '',
      selectedCourse: null,
      students: [],
      signInDialogVisible: false,
      signInSummary: null,
      canSignIn: true,
      defaultData:defaultData
    }
  },
  created() {
    this.currentDate = moment().format('YYYY年MM月DD日 dddd')
  },
  mounted() {
    this.loadTodayCourses()
    // 每30秒自动刷新一次课程列表
    this.refreshInterval = setInterval(() => {
      this.loadTodayCourses()
    }, 30000)
  },
  beforeDestroy() {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval)
    }
  },
  methods: {
    // 加载今日课程
    loadTodayCourses() {
      const data = {}
      const now = moment()
      data.year = now.format("YYYY")
      data.week = now.format("WW")
      data.day = now.format("dddd").toLowerCase()
      getTodayCourses(data).then(res => {
        if (res && res.data) {
          this.courses = res.data.map(course => {
            // 设置课程签到状态
            const timeArr =  this.defaultData[course.sort - 1].time.split("-")
            const now = moment()
            const dateStr = now.format("YYYY-MM-DD")
            let signInStatus = { type: 'default', text: '未开始' }
            if (now.isBefore(moment(dateStr +" "+ timeArr[0]))) {
              signInStatus = { type: 'default', text: '未开始' }
            } else if (now.isAfter(moment(dateStr +" "+ timeArr[1]))) {
              signInStatus = { type: 'info', text: '已结束' }
            } else {
              signInStatus = { type: 'primary', text: '进行中' }
            }

            return {
              ...course,
              signInStatus
            }
          })
        }
      }).catch(error => {
        // API请求失败时使用mock数据
        console.warn('获取今日课程失败', error)
      })
    },

    // 点击课程
    handleCourseClick(course) {
      console.log(course)
      this.selectedCourse = course
      this.loadCourseStudents()
      this.signInDialogVisible = true
    },

    // 加载课程学生列表
    loadCourseStudents() {
      if (!this.selectedCourse) return
      getCourseStudents({courseId : this.selectedCourse.courseId}).then(res => {
        if (res && res.rows) {
          this.students = res.rows.map(student => ({
            ...student,
            signed: false,
            signInTime: null
          }))
          // 获取签到记录
          this.loadSignInRecords()
        }
      }).catch(error => {
        // API请求失败时使用mock数据
        console.warn('获取学生列表失败', error)
      })
    },

    // 加载签到记录
    loadSignInRecords() {
      if (!this.selectedCourse) return
      const data = {
        courseId: this.selectedCourse.courseId,
        createTime: moment().format("YYYY-MM-DD HH:mm:ss"),
        sort: this.selectedCourse.sort,
      }
      getSignInRecords(data).then(res => {
        if (res && res.rows) {
          const signInMap = new Map()
          res.rows.forEach(record => {
            signInMap.set(record.studentId, record)
          })

          // 更新学生签到状态
          this.students.forEach(student => {
            const record = signInMap.get(student.id)
            if (record) {
              student.signed = true
              student.signInTime = record.createTime
            }
          })

          // 计算签到统计
          this.calculateSignInSummary()
          // 检查是否可以签到
          this.checkSignInStatus()
        }
      }).catch(error => {
        // API请求失败时使用mock数据
        console.warn('获取签到记录失败', error)
      })
    },

    // 计算签到统计
    calculateSignInSummary() {
      const signedCount = this.students.filter(student => student.signed).length
      const notSignedCount = this.students.length - signedCount

      this.signInSummary = {
        signedCount,
        notSignedCount
      }
    },

    // 检查是否可以签到
    checkSignInStatus() {
      if (!this.selectedCourse) {
        this.canSignIn = false
        return
      }
      const timeArr =  this.defaultData[this.selectedCourse.sort - 1].time.split("-")
      const now = moment()
      const dateStr = now.format("YYYY-MM-DD")
      this.canSignIn = now.isBefore(moment(dateStr +" "+ timeArr[1])) && now.isAfter(moment(dateStr +" "+ timeArr[0]))
    },

    // 单个学生签到
    singleSignIn(student) {
      if (!this.canSignIn) {
        this.$message.warning('当前不在签到时间段内')
        return
      }

      const signInData = {
        studentId: student.id,
        studentName:student.name,
        courseId: this.selectedCourse.courseId,
        courseName: this.selectedCourse.courseName,
        classId: this.selectedCourse.classId,
        className:this.selectedCourse.className,
        sort:this.selectedCourse.sort
      }

      studentSignIn(signInData).then(res => {
        this.loadSignInRecords()
      }).catch(error => {
        this.$message.error('签到请求失败')
        console.error('签到请求失败:', error)
      })
    },

    // 批量签到
    batchSignIn() {
      if (!this.canSignIn) {
        this.$message.warning('当前不在签到时间段内')
        return
      }

      this.$confirm('确定要为所有未签到的学生进行批量签到吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 找出所有未签到的学生
        const notSignedStudents = this.students.filter(student => !student.signed)

        if (notSignedStudents.length === 0) {
          this.$message.info('所有学生都已签到')
          return
        }

        // 逐个签到（实际项目中可以考虑批量API）
        let successCount = 0

        const signInData = notSignedStudents.map(student => {
          return {
            studentId: student.id,
            studentName: student.name,
            courseId: this.selectedCourse.courseId,
            courseName: this.selectedCourse.courseName,
            classId: this.selectedCourse.classId,
            className: this.selectedCourse.className,
            sort:this.selectedCourse.sort
          }
        })
          studentBatchSignIn(JSON.stringify(signInData)).then(res => {
            if (res.code === 200) {
              this.loadSignInRecords()
              // 当所有签到请求完成后更新统计
              if (successCount === notSignedStudents.length) {
                this.$message.success(`成功为 ${successCount} 名学生签到`)
              }
            }
          }).catch(() => {
            // 错误处理
          })
      }).catch(() => {
        // 取消操作
      })
    },

    // 刷新签到状态
    refreshSignInStatus() {
      this.loadSignInRecords()
      this.$message.success('签到状态已刷新')
    },

    // 关闭签到对话框
    closeSignInDialog() {
      this.signInDialogVisible = false
      // 延迟清空选中的课程，避免关闭动画卡顿
      setTimeout(() => {
        this.selectedCourse = null
        this.students = []
        this.signInSummary = null
      }, 300)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  font-size: 16px;
  color: #606266;
}

.course-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.course-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.course-info {
  padding: 20px;
}

.course-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.course-name {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.course-time {
  font-size: 14px;
  color: #606266;
  background-color: #f5f7fa;
  padding: 4px 12px;
  border-radius: 15px;
}

.course-details {
  margin-bottom: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.detail-item i {
  margin-right: 8px;
  color: #409eff;
}

.course-status {
  text-align: right;
}

.empty-state {
  grid-column: 1 / -1;
  padding: 60px 0;
}

.sign-in-dialog {
  max-height: 500px;
  overflow-y: auto;
}

.dialog-header {
  padding-bottom: 15px;
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.dialog-header h4 {
  margin: 0 0 5px 0;
  font-size: 18px;
  color: #303133;
}

.dialog-header p {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.sign-in-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.sign-in-summary {
  display: flex;
  gap: 20px;
  font-size: 14px;
}

.sign-in-summary span {
  padding: 4px 12px;
  background-color: #f5f7fa;
  border-radius: 15px;
}

.text-disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .course-list {
    grid-template-columns: 1fr;
  }

  .sign-in-actions {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}
</style>
